<template>
  <div class="echart" id="mychart" style="width:100%; height: 100%;"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  props: {
    symbol: {
      type: String,
      default: ''
    },
    timeActive: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null,
      chartOtherData: [], //服务端k线数据
      klineData: [], //k线图数据
      hourData: [], //charts表格小时数据
      xData: [],
      culomnColor: [], //颜色
      activatedFlag: false, //防止多次重复watch
    };
  },
  activated() {
    // this.getKlineData()
  },
  created() {
    this.activatedFlag = true;
    this.getKlineData()
  },
  deactivated() {
    this.activatedFlag = false;
    this.closeKlineData()
  },
  destroyed() {
    this.activatedFlag = false;
    this.closeKlineData()

  },
  computed: {
    socketMsgs() {
      return this.$websocket.getters.socketMsgs
    }
  },
  watch: {
    socketMsgs: function (data) {
      if (data.type == 'kline' && this.activatedFlag) {
        this.chartOtherData = data.data
        // 数据初始化
        this.initData();
        // 图标初始化
        this.initEcharts();
      }
    }
  },
  methods: {
    // 初始化
    init() {
      this.getKlineData()
    },
    // 取消订阅k线数据
    closeKlineData() {
      this.$websocket.dispatch('webSocketSend', { type: 'stop', method: 'kline' })
    },
    // 订阅k线数据
    getKlineData() {
      var timer = setInterval(() => {
        if (this.$websocket.getters.getState) {
          this.$websocket.dispatch('webSocketSend', { type: 'kline', symbol: this.symbol, period: this.timeActive })
          clearInterval(timer)
        }
      }, 1)
    },
    initData() {
      this.handleData();
      this.hourData = this.splitData(this.klineData);
      this.initxData();
    },
    initEcharts() {
      const option = {
        tooltip: {
          zIndex: 1,
          trigger: "axis",
          axisPointer: {
            type: "cross" //十字准星指示器
          },
          borderWidth: 1,
          borderColor: "#ccc",
          padding: 10,
          textStyle: {
            color: "#000"
          },
          formatter: function (param) {
            param = param[0];
            return [
              "Time: " + param.data[5] + '<hr size=1 style="margin: 3px 0">',
              "open: " + param.data[2] + "<br/>",
              "close: " + param.data[1] + "<br/>",
              "low: " + param.data[3] + "<br/>",
              "heigh: " + param.data[4] + "<br/>",
            ].join("");
          }
        },
        // 图像位置配置
        grid: [
          {
            top: "5%",
            left: "10%",
            right: "5%",
            height: "90%"
          },
        ],
        // 横坐标数据
        xAxis: [
          // 折线图
          {
            type: "category",
            data: this.xData,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            min: "dataMin",
            max: "dataMax"
          },

        ],
        // 纵坐标配置
        yAxis: [
          {
            scale: true,
            splitArea: {
              show: true
            }
          }
        ],
        dataZoom: [
          {
            type: "inside",
            xAxisIndex: [0, 1],
            start: 50, //展示的数据范围，默认为50%-100%
            end: 100
          }
        ],
        series: [
          {
            type: "line",
            data: this.hourData,
            symbol: "none", //无标记图案
            lineStyle: {
              width: 1
            }
          },
        ]
      };
      if (this.chart != null && this.chart != "" && this.chart != undefined) {
        this.chart.dispose();
      }
      this.chart = echarts.init(document.getElementById("mychart"));
      this.chart.setOption(option);
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        this.chart.resize();
      });
    },
    // 横坐标数据处理
    initxData() {
      for (let i = 0; i < this.klineData.length; i++) {
        this.xData[i] = this.klineData[i].datetime;
      }
      this.initCulomnColor();
    },
    // 初始化交易数据和交易柱状图颜色参数
    initCulomnColor() {
      this.culomnColor[0] = this.klineData[0].close > 0 ? 1 : -1;
      for (let i = 1; i < this.klineData.length; i++) {
        this.culomnColor[i] = this.klineData[i].close > this.klineData[i - 1].close ? 1 : -1;
      }
    },
    // 数据计算以及拆分，将json数据转为数组数据
    splitData(jsonData) {
      const hourData = [];
      for (let i = 0; i < jsonData.length; i++) {
        hourData.push([
          i,
          jsonData[i].close,
          jsonData[i].open,
          jsonData[i].low,
          jsonData[i].high,
          jsonData[i].datetime,
        ]);
      }
      return hourData;
    },
    // 处理k线图数据
    handleData() {
      const info = this.chartOtherData.reverse();
      for (let i = 0; i <= info.length - 1; i++) {
        let el = info[i]
        el.datetime = this.getFormatDate(el.id)
      }
      this.klineData = this.chartOtherData
    },
    // 反转数据
    reversePeople(array) {
      let newArr = []
      for (let i = array.length - 1; i >= 0; i--) {
        newArr[newArr.length] = array[i]
      }
      return newArr
    },
    // 格式化时间方法
    getFormatDate(value, formatter = 'MM-dd HH:mm') {
      if (!value) return ''
      const date = new Date(value * 1000)
      return formatter
        .replace('MM', date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1))
        .replace('dd', date.getDate() >= 10 ? date.getDate() : '0' + date.getDate())
        .replace('HH', date.getHours() >= 10 ? date.getHours() : '0' + date.getHours())
        .replace('mm', date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes())
    },
  }
};
</script>
